<template>
  <div class="channel-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>渠道管理</span>
          <el-button type="primary" @click="handleAdd">新增渠道</el-button>
        </div>
      </template>
      
      <!-- 搜索条件 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="渠道名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入渠道名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="路径">
            <el-input
              v-model="searchForm.path"
              placeholder="请输入渠道路径"
              clearable
            />
          </el-form-item>
          <el-form-item class="actions-item">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 数据表格 -->
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="channelsData.records"
          style="width: 100%"
          stripe
        >
          <el-table-column prop="id" label="ID" width="300" />
          <el-table-column prop="name" label="渠道名称" width="300" />
          <el-table-column prop="path" label="路径" width="400" />
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
               <div class="operation-buttons">
                    <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="searchForm.page"
            v-model:page-size="searchForm.pageSize"
            :page-sizes="[50,100,500,1000]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="channelsData.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
    
    <!-- 新增渠道对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增渠道"
      width="600px"
      :before-close="handleCloseAdd"
      center
      align-center
      :modal="true"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      class="custom-dialog"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="100px"
      >
        <el-form-item label="渠道名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入渠道名称" style="width: 100%" />
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="addForm.path" placeholder="请输入渠道路径（仅限英文）" oninput="value=value.replace(/[^a-zA-Z]/g,'')"  style="width: 100%" />
        </el-form-item>
         <div class="form-tip">
            提示：渠道路径仅限英文
          </div>
      </el-form>
       <template #footer>
        <div class="dialog-footer">
          <el-button 
            type="primary" 
            @click="handleSaveAdd" 
            :loading="addLoading"
          >
            添加
          </el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 编辑渠道对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑渠道"
      width="600px"
      :before-close="handleCloseEdit"
      center
      align-center
      :modal="true"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      class="custom-dialog"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="渠道名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入渠道名称" style="width: 100%" />
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="editForm.path" placeholder="请输入渠道路径（仅限英文）"  oninput="value=value.replace(/[^a-zA-Z]/g,'')" style="width: 100%" />
        </el-form-item>
         <div class="form-tip">
            提示：渠道路径仅限英文
          </div>
      </el-form>
        <template #footer>
            <div class="dialog-footer">
            <el-button 
                type="primary" 
                @click="handleSaveEdit" 
                :loading="editLoading"
            >
                保存
            </el-button>
            </div>
        </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllChannels, insertChannel, updateChannel, deleteChannel, getAllIssues } from '@/api/user.js'

export default {
  name: 'ChannelDistributor',
  setup() {
    // 状态
    const loading = ref(false)
    const addLoading = ref(false)
    const editLoading = ref(false)
    const addDialogVisible = ref(false)
    const editDialogVisible = ref(false)
    const addFormRef = ref(null)
    const editFormRef = ref(null)
    const currentEditId = ref(0)
    
    // 渠道数据
    const channelsData = ref({
      records: [],
      total: 0,
      size: 50,
      current: 1,
      pages: 1
    })
    
    // 联系人列表
    const contactsList = ref([])
    // 查询表单
    const searchForm = reactive({
      name: '',
      path: '',
      page: 1,
      pageSize: 50
    })
    
    // 新增表单
    const addForm = reactive({
      name: '',
      path: ''
    })
    
    // 编辑表单
    const editForm = reactive({
      name: '',
      path: ''
    })
    
    // 新增表单验证规则
    const addRules = {
      name: [
        { required: true, message: '请输入渠道名称', trigger: 'blur' }
      ],
      path: [
        { required: true, message: '请输入渠道路径', trigger: 'blur' }
      ]
    }
    
    // 编辑表单验证规则
    const editRules = {
      name: [
        { required: true, message: '请输入渠道名称', trigger: 'blur' }
      ],
      path: [
        { required: true, message: '请输入渠道路径', trigger: 'blur' }
      ]
    }
    
    // 加载渠道数据
    const loadChannels = async () => {
      try {
        loading.value = true
        
        // 构建请求参数
        const params = {
          pageNum: searchForm.page,
          pageSize: searchForm.pageSize
        }
        
        // 添加可选参数
        if (searchForm.name) params.name = searchForm.name
        if (searchForm.path) params.path = searchForm.path

        
        const response = await getAllChannels(params)
        //////console.log('渠道数据响应:', response)
        
        // 根据实际后端响应格式处理数据
        if (response && response.records) {
          channelsData.value = response
        } else {
          // 如果返回的数据格式不正确，设置为空数据
          channelsData.value = {
            records: [],
            total: 0,
            size: 50,
            current: 1,
            pages: 1
          }
          ElMessage.error('获取数据失败，返回格式不正确')
        }
      } catch (error) {
        //console.error('获取渠道数据失败:', error)
        ElMessage.error('获取数据失败，请重试')
        channelsData.value = {
          records: [],
          total: 0,
          size: 50,
          current: 1,
          pages: 1
        }
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      searchForm.page = 1 // 搜索时重置为第一页
      loadChannels()
    }
    
    // 重置
    const handleReset = () => {
      searchForm.name = ''
      searchForm.path = ''
      searchForm.page = 1
      searchForm.pageSize = 50
      loadChannels()
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      searchForm.pageSize = size
      loadChannels()
    }
    
    const handleCurrentChange = (current) => {
      searchForm.page = current
      loadChannels()
    }
    
    // 打开新增对话框
    const handleAdd = () => {
      // 重置表单
      addForm.name = ''
      addForm.path = ''
      
      if (addFormRef.value) {
        addFormRef.value.resetFields()
      }
      
      addDialogVisible.value = true
    }
    
    // 关闭新增对话框
    const handleCloseAdd = () => {
      addDialogVisible.value = false
    }
    
    // 保存新增渠道
    const handleSaveAdd = async () => {
      if (!addFormRef.value) return
      
      try {
        // 验证表单
        await addFormRef.value.validate()
        
        addLoading.value = true
        
        // 调用API
        const requestData = {
          name: addForm.name,
          path: addForm.path
        }
        
        const response = await insertChannel(requestData)
        
        if (response.code === 0 || response.code === 200) {
          ElMessage.success(response.message || response.result || '新增成功')
          handleCloseAdd()
          loadChannels() // 重新加载数据
        } else {
          ////console.log("新增失败 response:", response)
          ElMessage.error(response.message || response.result || '新增失败')
        }
      } catch (error) {
        //console.error('新增失败 error:', error)
        if (error !== 'cancel') {
          ElMessage.error('新增失败')
        }
      } finally {
        addLoading.value = false
      }
    }
    
    // 打开编辑对话框
    const handleEdit = (row) => {
      // 设置当前编辑ID
      currentEditId.value = row.id
      
      // 填充表单数据
      editForm.name = row.name
      editForm.path = row.path
   
      editDialogVisible.value = true
    }
    
    // 关闭编辑对话框
    const handleCloseEdit = () => {
      editDialogVisible.value = false
      currentEditId.value = null
      editFormRef.value?.resetFields()
    }
    
    // 保存编辑渠道
    const handleSaveEdit = async () => {
      if (!editFormRef.value) return
      
      try {
        // 验证表单
        await editFormRef.value.validate()
        
        editLoading.value = true
        
        // 调用API
        const requestData = {
          id: currentEditId.value,
          name: editForm.name,
          path: editForm.path
        }
        
        const response = await updateChannel(requestData)
        
        if (response.code === 0 || response.code === 200) {
          ElMessage.success(response.message || response.result || '修改成功')
          handleCloseEdit()
          loadChannels() // 重新加载数据
        } else {
          ElMessage.error(response.message || response.result || '修改失败')
        }
      } catch (error) {
        //console.error('修改失败 error:', error)
        if (error !== 'cancel') {
          ElMessage.error('修改失败')
        }
      } finally {
        editLoading.value = false
      }
    }
    
    // 删除渠道
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除渠道 "${row.name}" 吗？`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        
        const response = await deleteChannel(row.id)
        
        if (response.code === 0 || response.code === 200) {
          ElMessage.success(response.message || response.result || '删除成功')
          loadChannels() // 重新加载数据
        } else {
          ElMessage.error(response.message || response.result || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          //console.error('删除失败 error:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    // 加载联系人列表
    // const loadContactsList = async () => {
    //     try {
    //         const response = await getAllIssues()
    //         if (Array.isArray(response)) {
    //         contactsList.value = response
    //         } else if (response.code === 0) {
    //         contactsList.value = response.data || []
    //         }
    //     } catch (error) {
    //         //console.error('获取联系人列表失败:', error)
    //         ElMessage.error('获取联系人列表失败')
    //         contactsList.value = []
    //     }
    //     }

    // 根据issues字符串获取联系人名称列表
        const getContactNames = (issuesStr) => {
            if (!issuesStr) return []
            
            // 将issues字符串分割成ID数组
            const issueIds = issuesStr.split(',').map(id => parseInt(id))
            
            // 筛选出匹配的联系人
            return contactsList.value.filter(contact => issueIds.includes(contact.id))
        }
    
    // 组件挂载时加载数据
    loadChannels()
    // loadContactsList()
    
    return {
      // 状态
      loading,
      addLoading,
      editLoading,
      addDialogVisible,
      editDialogVisible,
      addFormRef,
      editFormRef,
      currentEditId,

      // 数据
      channelsData,
      searchForm,
      addForm,
      editForm,
      addRules,
      editRules,
      contactsList,

      // 方法
      loadChannels,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleCloseAdd,
      handleSaveAdd,
      handleEdit,
      handleCloseEdit,
      handleSaveEdit,
      handleDelete,
      getContactNames
    }
  }
}
</script>

<style scoped>

/* 美化表单提示样式 */
.custom-dialog .form-tip {
  font-size: 12px;
  color: #999;
  margin-left: 80px;
  margin-top: -5px;
  margin-bottom: 50px;
}

.custom-dialog .display-group {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.custom-dialog .display-group .radio-group {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 24px;
  flex: 1;
}

.custom-dialog .display-group .el-radio {
  display: flex;
  align-items: center;
  margin-right: 0;
}

.custom-dialog .display-group .el-radio__label {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
  margin-left: 8px;
}

/* 弹框样式 */
.dialog-footer {
  text-align: center;
  padding: 0;
}

.dialog-footer .el-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 6px;
}

/* 美化表单样式 */
.custom-dialog .el-form-item {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  background: transparent;
  padding: 0;
  border-radius: 0;
  box-shadow: none;
  border: none;
  transition: all 0.3s ease;
}

.custom-dialog .edit-form-input {
  margin-bottom: 0 !important;
  width: 100% !important;
  flex: 1 !important;
  min-width: 0 !important;
  max-width: 100% !important;
}

/* 确保所有输入框宽度为100% */
.custom-dialog .el-form-item__content .el-input {
  width: 100% !important;
  flex: 1 1 auto !important;
  min-width: 0 !important;
  max-width: 100% !important;
  display: flex !important;
}

.custom-dialog .el-form-item__content .el-input__wrapper,
.custom-dialog .el-form-item__content .el-input_wrapper {
  width: 100% !important;
  flex: 1 1 auto !important;
  min-width: 0 !important;
  max-width: 100% !important;
  display: flex !important;
}

.custom-dialog .el-form-item__content .el-input__inner,
.custom-dialog .el-form-item__content .el-input_inner {
  width: 100% !important;
  min-width: 0 !important;
  max-width: 100% !important;
}

.custom-dialog .el-form-item:hover {
  box-shadow: none;
  border-color: transparent;
}

.custom-dialog .el-form-item__label {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  height: 40px;
  line-height: 40px;
  font-weight: 500;
  color: #333;
  min-width: 80px;
  padding-right: 12px;
}

.custom-dialog .el-form-item__content {
  display: flex !important;
  align-items: center;
  flex: 1 !important;
  height: 40px;
  min-width: 0 !important;
  width: 100% !important;
  max-width: 100% !important;
}

.custom-dialog .el-radio-group {
  display: flex;
  gap: 24px;
  align-items: center;
}

.custom-dialog .el-radio {
  margin-right: 0;
  display: flex;
  align-items: center;
  font-weight: 500;
}

.custom-dialog .el-radio__label {
  font-size: 14px;
  color: #666;
}

/* 最高优先级修复双边框 */
.custom-dialog .el-form-item :deep(.el-input__wrapper) {
  border: 1px solid #dcdfe6 !important;
  border-radius: 6px !important;
  box-shadow: none !important;
  outline: none !important;
}

.custom-dialog .el-form-item :deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc !important;
  box-shadow: none !important;
}

.custom-dialog .el-form-item :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff !important;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1) !important;
}

.custom-dialog .el-form-item :deep(.el-input__inner) {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
}



/* 美化按钮样式 */
.custom-dialog .dialog-footer .el-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.custom-dialog .dialog-footer .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.5);
}

.custom-dialog .dialog-footer .el-button:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.4);
}

/* 自定义弹框样式 */
.custom-dialog :deep(.el-dialog) {
  margin: 0 auto !important;
  top: 10vh !important;
  transform: none !important;
  max-height: 80vh;
  overflow-y: auto;
  border-radius: 12px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  border: none;
}

.custom-dialog :deep(.el-dialog__header) {
  text-align: center;
  padding: 24px 24px 16px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

.custom-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: white;
}

.custom-dialog :deep(.el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: none;
}

.custom-dialog :deep(.el-dialog__headerbtn:hover) {
  background: rgba(255, 255, 255, 0.3);
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 24px;
  background: #fafafa;
}

.custom-dialog :deep(.el-dialog__footer) {
  padding: 16px 24px 24px;
  background: #fafafa;
  border-radius: 0 0 12px 12px;
}

/* 美化遮罩层 */
.custom-dialog :deep(.el-overlay) {
  background-color: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(4px);
}

.custom-dialog :deep(.el-dialog__wrapper) {
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 10vh;
}

.channel-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.search-container {
  margin-bottom: 20px;
}

.search-form {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  display: flex;
  flex-wrap: wrap;
  gap: 12px 20px;
}
.search-form :deep(.el-form-item) {
  margin-bottom: 0;
}
.search-form .actions-item {
  display: flex;
  align-items: center;
  gap: 10px;
}
.search-form .actions-item :deep(.el-form-item__content) {
  display: flex;
  align-items: center;
  gap: 10px;
}
.search-form :deep(.el-input__wrapper) {
  border: 1px solid #dcdfe6 !important;
  border-radius: 6px !important;
  box-shadow: none !important;
  outline: none !important;
}
.search-form :deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc !important;
  box-shadow: none !important;
}
.search-form :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff !important;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1) !important;
}
.search-form :deep(.el-input__inner) {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
}
:deep(.search-form .el-form-item:nth-child(1) .el-input),
:deep(.search-form .el-form-item:nth-child(2) .el-input) {
  width: 200px;
}
:deep(.search-form .el-form-item:nth-child(1) .el-input__wrapper),
:deep(.search-form .el-form-item:nth-child(2) .el-input__wrapper) {
  transition: none !important;
}
.table-container {
  width: 100%;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
.operation-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: center;
}

.operation-buttons .el-button {
  margin: 0;
}
</style>